import React, { Fragment, useState, useEffect } from 'react';
import { Modal, Form, Input, message, Upload, Icon, Button } from 'antd';
import BraftEditor from 'braft-editor';
import { uploadFile } from '@/utils/fileUpload';
import { useSendMail } from '@/pages/Mail/hooks';
import { history } from 'umi';
import getTemp from './getTemp';
import Styles from './SendMail.less';
// import { sendMail } from '@/services/myRecruit/talentPool';
// import { sendMail } from '@/services/myRecruit/talentPool';
import { Attachment } from '../../../Mail/components';

const formItemLayout = {
    labelCol: {
        md: { span: 5 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 19 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};
const attachLayout = {
    wrapperCol: {
        md: { span: 19, offset: 5 },
        xs: { span: 24, offset: 24 },
        sm: { span: 24, offset: 0 }
    }
};
const controls = [
    'undo',
    'redo',
    'separator',
    'font-size',
    'line-height',
    'letter-spacing',
    'separator',
    'text-color',
    'bold',
    'italic',
    'underline',
    'strike-through',
    'separator',
    'superscript',
    'subscript',
    'remove-styles',
    'emoji',
    'separator',
    'text-indent',
    'text-align',
    'separator',
    'headings',
    'list-ul',
    'list-ol',
    'blockquote',
    'code',
    'separator',
    // 'media',
    'link',
    'hr',
    'separator',
    'clear'
];
const SendMail = ({ form, onOk, onCancel, visible, setMailModle, data = {}, ...rest }) => {
    const { getFieldDecorator } = form;
    const { tempInfo = {} } = data;
    const { talentEmail = '' } = tempInfo;
    const temp = getTemp({ tempInfo });
    const initContent = BraftEditor.createEditorState(temp);
    const [uploadFiles, setUploadFiles] = useState([]);
    const [previewList, setPreviewList] = useState([]);
    // 生成图片预览数组
    useEffect(() => {
        setPreviewList([...uploadFiles.map(item => ({ uid: item.uid, fileName: item.name, fileSize: item.size }))]);
    }, [uploadFiles]);
    // 发送候选人邮件
    const [sendParams, setSendParams] = useState(null); // 邮件发送内容
    const { loading, isSuccess, method } = useSendMail(sendParams); // 发邮件
    const handleMailSend = () => {
        form.validateFields((err, values) => {
            if (!err) {
                const { email, subject, content } = values;
                setSendParams({
                    to: email,
                    cc: '',
                    subject,
                    content: content.toHTML(),
                    uploadFiles
                });
            }
        });
    };
    // 不允许添加尺寸大于100M的文件
    const myValidateFn = file => {
        if (file.size > 1024 * 1024 * 100) {
            message.error('Size is greater than 1M!');
            return false;
        }
        return true;
    };
    const myUploadFn = param => {
        const params = {
            fileInfo: param
        };
        return uploadFile(params); // 图片转base64
    };
    const handleEditorChange = editorStates => {
        form.setFieldsValue({ content: editorStates });
    };
    // 上传附件相关方法
    // 上传参数
    const uploadParam = {
        name: 'file',
        accept: '*',
        className: 'upload-list-inline',
        defaultFileList: [],
        multiple: true,
        showUploadList: false,
        fileList: uploadFiles,
        beforeUpload(file, fileList) {
            for (let i = 0; i < fileList.length; i += 1) {
                const isLimit = file.size / 1024 / 1024 < 30;
                if (!isLimit) {
                    message.error(`文件：${file.name} 超过30MB！`);
                    return false;
                }
            }
            setUploadFiles([...uploadFiles, ...fileList]);
            return false;
        }
    };
    // 删除图片
    const onRemove = e => {
        uploadFiles.splice(
            uploadFiles.findIndex(item => item.uid === e.uid),
            1
        );
        setUploadFiles([...uploadFiles]);
    };
    React.useEffect(() => {
        if (isSuccess) {
            // visible=false
            method.resetSuccess();
            setMailModle(false);
            history.push({
                pathname:
                    window.location.pathname === '/office/personnelManagement/recruit/interview/add'
                        ? '/office/personnelManagement/recruit/interview'
                        : '/personal/portal/recruit/interview'
            });
        }
    }, [isSuccess]);
    return (
        <div>
            <Modal
                confirmLoading={loading}
                title="通知候选人"
                width={900}
                id="notice"
                onOk={handleMailSend}
                onCancel={() => {
                    onCancel();
                    setUploadFiles([]);
                }}
                visible={visible}
                destroyOnClose
                {...rest}
            >
                <Form layout="horizontal" {...formItemLayout} className={Styles.sendMail}>
                    {visible && (
                        <Fragment>
                            <Form.Item label="候选人邮箱">
                                {getFieldDecorator('email', {
                                    initialValue: talentEmail,
                                    rules: [
                                        {
                                            type: 'email',

                                            message: '请输入正确格式的邮箱！'
                                        },
                                        {
                                            required: true,
                                            message: '请输入邮箱！'
                                        }
                                    ]
                                })(<Input style={{ width: '567px' }} />)}
                            </Form.Item>
                            <Form.Item label="邮件主题">
                                {getFieldDecorator('subject', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请输入邮件主题！'
                                        }
                                    ]
                                })(<Input style={{ width: '567px' }} />)}
                            </Form.Item>
                            <Form.Item
                                // className={style.noticeTextAdd}
                                label="邮箱内容"
                                wrapperCol={{ md: { span: 16 } }}
                            >
                                {getFieldDecorator('content', {
                                    initialValue: initContent,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请输入邮件内容',
                                            validator: (_, value, callback) => {
                                                if (value.isEmpty()) {
                                                    callback('请输入邮件内容');
                                                } else {
                                                    callback();
                                                }
                                            }
                                        }
                                    ]
                                })(
                                    <BraftEditor
                                        onChange={handleEditorChange}
                                        media={{
                                            uploadFn: myUploadFn,
                                            validateFn: myValidateFn,
                                            // onChange: fileChange,
                                            accepts: {
                                                image: 'image/png,image/jpeg,image/gif'
                                            }
                                        }}
                                        controls={controls}
                                        excludeControls={['fullscreen']}
                                        imageControls={[
                                            {
                                                onClick: block => {
                                                    console.log(block);
                                                } // 指定控件点击后的回调，参数为当前图片的block对象
                                            },
                                            'size',
                                            'remove'
                                        ]}
                                        style={{
                                            border: '1px solid #d9d9d9',
                                            borderTopWidth: '1.02px',
                                            borderRadius: '4px',
                                            marginTop: '4px'
                                        }}
                                        // className={style.paddingBraftEditor}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item style={{ padding: '8px 0', marginBottom: 4 }} {...attachLayout}>
                                {form.getFieldDecorator('files')(
                                    <>
                                        <Upload {...uploadParam}>
                                            <Button disabled={uploadFiles.length >= 10}>
                                                <Icon type="paper-clip" /> 添加附件
                                            </Button>
                                        </Upload>
                                        <span style={{ fontSize: 12, color: '#F3BA00', margin: '0 17px 0 8px' }}>
                                            (最大30MB)
                                        </span>
                                        <span style={{ color: '#8C8C8C', fontSize: 12 }}>
                                            支持扩展名：.rar .zip .doc .docx .pdf .jpg等
                                        </span>
                                    </>
                                )}
                                {previewList && previewList.length > 0 && (
                                    <div style={{ marginTop: 16 }}>
                                        <Attachment attachmentList={previewList} type="del" onClick={onRemove} />
                                    </div>
                                )}
                            </Form.Item>
                        </Fragment>
                    )}
                </Form>
            </Modal>
        </div>
    );
};

export default SendMail;
